<template>
    <div>
        <div class="search">
          <el-form  :model="formData" inline size="small">
              <el-form-item label="时间">
                <el-date-picker
                  v-model="formData.begin"
                  type="date"
                  format="yyyy年 MM 月 dd 日"
                  value-format="yyyy/MM/dd"
                  placeholder="开始时间">
                  </el-date-picker>
                  <span style="margin: 0 10px;">至</span>
                  <el-date-picker
                  v-model="formData.end"
                  type="date"
                  format="yyyy年 MM 月 dd 日"
                  value-format="yyyy/MM/dd"
                  placeholder="结束时间">
                  </el-date-picker>
              </el-form-item>
              <el-form-item label="排序">
                  <el-select v-model="formData.orderType" placeholder="请选择" class="form-item">
                      <el-option label="正序" :value="0"></el-option>
                      <el-option label="倒序" :value="1"></el-option>
                  </el-select>
              </el-form-item>
              <el-form-item>
                  <el-button type="primary" icon="el-icon-search" @click="handleGetTableList">查询</el-button>
                  <el-button type="success" icon="el-icon-postcard" @click="handleShowCount">计算参数</el-button>
                  <el-button type="success" icon="el-icon-picture-outline" @click="handleAddImage">指标展示图</el-button>
                  <el-button type="success" icon="el-icon-upload2" @click="exportToExcel">导出表格</el-button>
              </el-form-item>
          </el-form>
        </div>
        <div class="dataWrapper"  v-loading="tableLoading" element-loading-text="数据加载中，请稍后"
    element-loading-spinner="el-icon-loading">
            <BoxWithTitle title="目录" icon="&#xe6f2;" class="menu-wrapper">
                <div  class="menu-tree">
                    <treeMenu :treeData="menuTree" name="indeX_NAME" @menuLeftClick="handleMenuLeftClick" ref="treeMenu"/>
                </div>
            </BoxWithTitle>
            <div class="right-wrapper boxWrapper">
                <el-collapse v-model="activeNames" @change="handleChangeCollapse">
                    <el-collapse-item title="公式" name="1">
                        <div v-if="jCriteria.length > 0" class="formulaWrapper">
                          <p v-for="(item,index) in jCriteria" :key="index">{{ item }}</p>
                        </div>
                    </el-collapse-item>
                    <el-collapse-item title="数据展示" name="2">
                        <onlineTale :tableTitleList="tableTitleList" :tableData="tableData" :tableHeight="veTableHeight"/>
                    </el-collapse-item>
                    <el-collapse-item title="图表展示" name="3">
                    <template slot="title">
                        <div class="chartTitleBox">
                          <div>图表展示</div>
                          <div>
                            <el-radio-group v-model="chartType" size="mini" @change="handleChangeChartType"> 
                              <el-radio-button :label="0">评价结果</el-radio-button>
                              <el-radio-button :label="1">过程线</el-radio-button>
                              <el-radio-button v-for="(item,index) in this.bwtList" :key="index" 
            :label="index + 2">{{ item.bwtPrm.bwtName }}</el-radio-button>
                            </el-radio-group>
                          </div>
                        </div>
                      </template>
                        <div id="chartBar" class="chartLine" style="width:100%" v-show="chartType == 0"></div>
                        <onlineChart v-show="chartType == 1" :myChartLineData="myChartLineData"/>

                        <div v-show="chartType >= 2 ">
                          <onlineImage :operateForm="bwtData"/>
                        </div>

                    </el-collapse-item>
                </el-collapse>
            </div>

            <el-dialog title="计算参数" :visible.sync="handleShowCalculation"
            v-dialogDrag width="70%">
              <div class="dialog-wrapper">
                <div class="controlTitle">指标控制值</div>
                <controlValue :indeX_ID="indeX_ID" showControl/>
                <div class="controlTitle">指标参数</div>
                <indicatorParameters :indeX_ID="indeX_ID" />
              </div>
            </el-dialog>

            <el-dialog title="指标展示图设置" :visible.sync="imageTableVisible"
            v-dialogDrag width="70%">
              <div class="dialog-wrapper">
                <ImageAssociation :indeX_ID="indeX_ID" :stationId="stationId"/>
              </div>
            </el-dialog>
        </div>
    </div>
</template>
<script>
import treeMenu from '../../base/treeMenu.vue'
import BoxWithTitle from '../../base/BoxWithTitle.vue'
import {scuRmIndexList,getCalcDescribe,indexResultList,GetIndexLink}from '@/api/https'
import onlineTale from './onlineTale.vue';
import onlineChart from './onlineChart.vue';
import controlValue from '@/components/base/controlValue.vue';
import indicatorParameters from '@/components/base/IndicatorParameters.vue'
import ImageAssociation from '@/components/base/ImageAssociation.vue';
import onlineImage from './onlineImage.vue'
import * as echarts from 'echarts';
import XLSX from 'xlsx/dist/xlsx.full.min'; 
export default ({
    props:{
        stationId:{
            type:[String,Number],
            default:0
        }
    },
    components:{BoxWithTitle,treeMenu,onlineTale,onlineChart,controlValue,indicatorParameters,ImageAssociation,onlineImage},
    data() {
        return {
            menuTree:[],
            indeX_ID:'',
            index_CLASS_ID:'',
            activeNames:['2','3'],
            jCriteria:[],
            tableTitleList:[],
            tableData:[],
            TotalCount:1,
            pageIndex:1,
            myChartBar:null,
            chartType:0,
            veTableHeight:'calc(100vh - 620px)',
            handleShowCalculation:false,
            tableLoading:false,
            imageTableVisible:false,
            bwtList:[],
            myChartLineData:[],
            bwtData:{},
            formData:{}
        }
    },
     watch:{
        'stationId':{
            handler(newVal,oldVal){
              this.clearData()
              if(this.myChartBar){
                this.myChartBar.clear()
              }
              this.menuTree = []
              this.getMenuList()
            }
        },
    },
    activated(){
      if(this.myChartBar != null){
        this.myChartBar.resize()
      }
    },
    deactivated(){
      if(this.myChartBar){
        this.myChartBar.clear()
      }
    },
    beforeDestroy(){
      if(this.myChartBar){
        this.myChartBar.clear()
        this.myChartBar.dispose()
        this.myChartBar = null
      }
    },
    mounted(){
      const toDay = new Date()
      this.formData = {
          begin:(toDay.getFullYear() - 1) + '/' + (toDay.getMonth() + 1) + '/' + (toDay.getDate()),
          end:(toDay.getFullYear()) + '/' + (toDay.getMonth() + 1) + '/' + (toDay.getDate()),
          orderType:1,
      }
        this.getMenuList()
    },
    methods:{
        getMenuList(){
            scuRmIndexList({
                STATION_ID:this.stationId,
                CATALOG:0
            }).then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    this.menuTree = res.data
                    this.findLeafNodes(this.menuTree);
                    this.$nextTick(()=>{
                        this.$refs.treeMenu.$refs.tree.setCurrentKey(this.indeX_ID);
                        this.handleGetTableList()
                    })
                }else{
                  this.menuTree = []
                }
            })
        },
        findLeafNodes(data) {
            if (data[0].children == null || data[0].children.length === 0){
                this.indeX_ID = data[0].id
                this.index_CLASS_ID = data[0].index_CLASS_ID
                return
            }else{
                this.findLeafNodes(data[0].children);
            }
        },
        handleMenuLeftClick(data){
          this.clearData()
          this.indeX_ID = data.indeX_ID
          this.indeX_CLASS_ID = data.indeX_CLASS_ID
          this.handleGetTableList()
          if(this.myChartBar){
            this.myChartBar.clear()
          }
        },
        clearData(){
          this.indeX_ID =''
          this.indeX_CLASS_ID = ''
          this.tableData = []
          this.tableTitleList = []
          this.bwtList = []
        },
        handleGetTableList(){
          this.tableLoading = true
          this.chartType = 0
          this.handleGetDescribe()
          indexResultList({
            indeX_ID:this.indeX_ID,
            begin:this.formData.begin,
            end:this.formData.end,
            pageIndex:1,
            PageSize:50,
            orderType:this.formData.orderType
          }).then(res=>{
            if(res.isSuccess && res.data){
              // 确认表头信息
              let tableTitleList = []
              if(res.data.compNames.length > 0){
                res.data.compNames.forEach((item,index)=>{
                  tableTitleList.push({
                    'title':item,
                    'value':res.data.comPs[index]
                  })
                })
              }
              this.tableTitleList = tableTitleList

               // 数据部分
              let copyData = []
              const chartData = []
              if(res.data.node && res.data.node.length > 0){
                res.data.node.forEach((item,index)=>{
                  const data = {
                    index:index+1,
                    picktime:item.picktime, 
                    pointName:item.pointName,
                    check:item.check,
                    chaeckuserName:item.chaeckuserName,
                    id:item.id
                  }
                  if(this.tableTitleList.length > 0){
                    this.tableTitleList.forEach((subItem,subIndex)=>{
                      data[subItem.value] = item.comPs[subIndex]
                    })
                  }
                  copyData.push(data)

                  //画图表
                const compNameIndex = res.data.compNames.findIndex(item=> item == '评价结果'  || item == '评判结果')
                  
                  if(compNameIndex > -1){
                    const time = item.picktime.split(' ')
                    chartData.push({
                      date:time[0],
                      type:item.comPs[compNameIndex]
                    })
                  }
                })
                
                this.tableData = [...copyData]

                this.getChartLineAndImage(res.data.comPs,res.data.compNames[0])

                if(!this.myChartBar){
                  let chartDomBar =  document.getElementById('chartBar')
                  this.myChartBar = echarts.init(chartDomBar,null,{locale:"ZH"});
                }
                this.$nextTick(()=>{
                  this.drawChartBar(chartData,res.data.node[0].pointName)
                })
              }else{
                this.TotalCount = 1
                this.tableData = []
                this.tableTitle = []
                this.myChartLineData = []
              }
              this.tableLoading = false
            }else{
              this.tableLoading = false
              this.TotalCount = 1
              this.tableData = []
              this.tableTitle = []
              this.myChartLineData = []
            }
          })
        },
        getChartLineAndImage(comPs,compName){
          this.bwtList = []
          GetIndexLink({
                begin:this.formData.begin,
                comp:comPs,
                compName:compName,
                end:this.formData.end,
                indeX_ID:this.indeX_ID,
                statioN_ID:this.stationId
            }).then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    if(res.data[0].catalog == 0 && res.data[0].gcxData &&  res.data[0].gcxData.length > 0){
                        this.myChartLineData = res.data[0].gcxData[0].data            
                    }else{
                      this.myChartLineData = []
                    }

                    res.data.forEach(item=>{
                      if(item.bwtPrm){
                        // 变位图数据
                        this.bwtList.push(item)
                      }
                    })
                }
            })
        },
        drawChartBar(chartData,name){
          const typeConfig = {
            '正常': { color: '#03b009', height: 1 },
            '轻微异常': { color: '#0b6ddd', height: 2 },
            '一般异常': { color: '#fc8452', height: 3 },
            '严重异常': { color: '#f00', height: 4 }
         }

          const _chartData = chartData.map(item => {
            const config = typeConfig[item.type] || { 
              color: '#999', 
              height: 1
            };
            return {
              value: [item.date, config.height],
              itemStyle: { color: config.color }
            };
          });

          let option = {
            title: {
              left: 'center',
              text: name,
              textStyle:{
                fontSize:'14'
              }
            },
            tooltip: {
              trigger: 'axis',
              formatter: params => {
                  const dataItem = chartData.find(item => item.date === params[0].value[0]);
                  return `日期: ${dataItem.date}<br/>评价结果: ${dataItem.type}`;
              }
            },
            grid: {
              top:'15%',
              left: '2%',
              right: '2%',
              bottom: '10%',
              containLabel: true, 
              borderWidth:1,
              show: true,
              borderColor: '#000',
            },
            toolbox: {
              feature: {
                dataZoom: {
                  yAxisIndex: 'none'
                },
                restore: {},
                saveAsImage: {}
              }
            },
            xAxis: {
              type: 'category',
              boundaryGap: ['2%', '2%'],
              show: true, 
              axisLine: {
                show: true, 
              },
              splitLine: {
                show: true, 
                lineStyle: {
                  type: 'dashed',
                  color: '#a8a8a8',
                },
              },
            },
            yAxis: {
              type: 'value',
              min: 0,
              max: 5,
              axisLine: {
                show: true,
              },
              splitLine: {
                show: true,
                lineStyle: {
                  type: 'dashed',
                  color: '#a8a8a8',
                },
              },
              axisLabel: {
                  formatter: value => {
                      const labels = {
                          1: '正常',
                          2: '轻微异常',
                          3: '一般异常',
                          4: '严重异常'
                      };
                      return labels[value] || '';
                  }
              }
            },
            dataZoom: [
              {
                type: 'inside',
              },
            ],
            series: [
              {
                data: _chartData,
                type: 'bar',
                name:'评价结果',
              }
            ]
          };
          
          if (option && typeof option === 'object') {
            this.myChartBar.setOption(option, true);
          }
        },
        handleGetDescribe(){
            getCalcDescribe({
                index_CLASS_ID:this.index_CLASS_ID
            }).then(res=>{
                if(res.isSuccess && res.data){
                  this.jCriteria = res.data.split(';')
                }else{
                  this.jCriteria = []
                }
            })
        },
        handleChangeCollapse(val){
          if(val.length == 1 && val[0] == '2'){
            this.veTableHeight = 'calc(100vh - 400px)'
          }else{
            this.veTableHeight = 'calc(100vh - 620px)'
          }
        },
        handleShowCount(){
          this.handleShowCalculation = true
        },
        handleAddImage(){
          this.imageTableVisible = true
        },
        exportToExcel(){
            if(this.tableData.length <= 0){
                this.$message.warning('暂无数据可以下载！')
                return false
            }

            this.$nextTick(() => {
              try {
                console.log('XLSX:', XLSX);  // 调试确认
                if (!XLSX?.utils) throw new Error('xlsx 库加载失败');

                const table = document.querySelector('#exportTable');
                if (!table) throw new Error('表格不存在');

                const wb = XLSX.utils.table_to_book(table, { raw: true });
                const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
                saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'data.xlsx');
              } catch (error) {
                console.error('导出失败:', error);
                this.$message.error(`导出失败: ${error.message}`);
              }
            });
        },
        handleChangeChartType(){
          if(this.chartType >= 2){
            this.bwtData = this.bwtList[this.chartType - 2].bwtPrm
          }
        }
    }
})
</script>
<style scoped lang="scss">
.search{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    background: #fff;
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;
    padding:0 20px;
    box-sizing: border-box;
}
.dataWrapper{
    display: grid;
    grid-template-columns: 340px 1fr;
    height: calc(100vh - 230px);
    margin-top:10px;
    .menu-wrapper{
       width: 340px;
        height: calc(100vh - 230px);
        flex-shrink: 0;
        .menu-tree{
            height: calc(100vh - 280px);
            overflow-y: auto;
        }
    }
    .right-wrapper{
        height: calc(100vh - 230px);
        overflow: auto;
        margin-left:10px;
        padding:0px 20px;
        box-sizing: border-box;
    }    
}
.chartLine{
  width: 100% !important;
  height: 240px;
  z-index: 99;
}
::v-deep .el-collapse-item__content{
  padding-bottom:0px !important
}
.chartTitleBox{
  width:100%;
  display: flex;
  flex-direction: row;
  justify-content:space-between;
  padding-right: 20px;
}
.controlTitle{
  font-weight: bold;
  line-height: 35px;
  color:#000;
}
.dialog-wrapper{
  height: calc(100vh - 300px);
  overflow-y:auto ;
}
</style>
